<template>
  <div class="user-management-container">
    <!-- 查询表单 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="姓名">
              <el-input
                v-model="searchForm.loginName"
                placeholder="请输入姓名"
                clearable
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="用户ID">
              <el-input
                v-model="searchForm.userId"
                placeholder="请输入用户ID"
                clearable
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12" :offset="6" class="text-right">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="openAddDialog">
              添加用户
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <el-table :data="userList" stripe style="width: 100%">
        <el-table-column prop="avatar" label="头像" width="100">
          <template #default="{ row }">
            <el-avatar :size="50" :src="row.avatar" />
          </template>
        </el-table-column>
        <el-table-column prop="loginName" label="姓名" width="120" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            {{ row.sex === '1' ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="phoneNumber" label="手机号" width="150" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="'0'"
              :inactive-value="'1'"
              active-text="启用"
              inactive-text="禁用"
              @change="toggleStatus(row)"
            />
          </template>
        </el-table-column>
        <!-- <el-table-column prop="userId" label="用户ID" width="150" /> -->
        <el-table-column prop="birthday" label="出生日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.birthday) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row.userId)"
            >
              删除
            </el-button>
            <el-button type="primary" size="small" @click="divisonRole(row)">
              分配角色
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="loginName">
          <el-input v-model="userForm.loginName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userForm.sex">
            <el-radio :label="'1'">男</el-radio>
            <el-radio :label="'0'">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="userForm.phoneNumber" placeholder="请输入手机号" />
        </el-form-item>
        <!-- <el-form-item label="用户ID" prop="userId">
          <el-input
            v-model="userForm.userId"
            :disabled="isEditing"
          />
        </el-form-item> -->
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker
            v-model="userForm.birthday"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 弹出框给用户分配角色  -->
    <el-dialog
      title="选择角色"
      v-model="visible"
      width="850px"
      top="5vh"
      append-to-body
    >
      <select-role
        v-if="visible"
        ref="selectR"
        :userId="chooseUserId"
        @cancel="handleCancel"
        @confirm="handleSelectRole"
      ></select-role>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, toRaw } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import selectRole from '../role/index.vue'
import {
  reqUsers,
  reqUserAdd,
  reqUserUpdate,
  requserOne,
  reqUserDel,
} from '@/api/users'
import {
  UserResp,
  UserListResponse,
  emptyPageInfo,
  PageQuery,
  PageInfo,
  R,
} from '@/api/users/type'
import { User } from '@/views/acl/user/ts/user/type'

import { reqAssignedRole } from '@/api/role/index'
import { AssignRole } from '@/api/role/type'


const chooseUserId = ref<number>(-1)
const visible = ref(false)
const selectedRoles = ref<number[]>([]) // 子组件回传的角色 id
const pageInfo = reactive<PageInfo>(emptyPageInfo())

// 表单数据类型
interface UserForm {
  id?: number
  loginName?: string
  sex?: string
  avatar?: string
  phoneNumber?: string
  userId?: number
  birthday?: string
}

// 搜索表单
const searchForm = reactive({
  loginName: '',
  userId: '',
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

// 用户列表数据
const userList = ref<UserResp[]>([])

// 对话框相关
const dialogVisible = ref(false)
const isEditing = ref(false)
const userFormRef = ref<FormInstance>()
const userForm = reactive<UserForm>({
  loginName: '',
  sex: '',
  avatar: '',
  phoneNumber: '',
  birthday: '',
})

// 表单验证规则
const userRules = reactive({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
  ],
  userId: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
  birthDate: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
})

// 对话框标题计算属性
const dialogTitle = computed(() => (isEditing.value ? '编辑用户' : '添加用户'))

// 初始化加载数据
onMounted(() => {
  // 模拟API请求
  setTimeout(() => {
    fetchUserList()
  }, 500)
})

// 获取用户列表
const fetchUserList = async () => {
  const query: PageQuery = {
    filterData: { ...searchForm },
    pageInfo: toRaw(pageInfo),
  }
  query.pageInfo.pageIndex = pagination.currentPage;
  query.pageInfo.pageSize = pagination.pageSize;
  let result: UserListResponse = await reqUsers(query)
  if (result.code == 200) {
    userList.value = result.data.records
    pagination.total = result.data.total
  } else {
    return Promise.reject(new Error(result.message))
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.loginName = ''
  searchForm.userId = ''
  handleSearch()
}

// 打开添加对话框
const openAddDialog = () => {
  Object.assign(userForm, {})
  dialogVisible.value = true
  isEditing.value = false
}

// 处理编辑
const handleEdit = (row: UserResp) => {
  Object.assign(userForm, row)
  dialogVisible.value = true
  isEditing.value = true
}

/* 子组件点击“确定”后回调 */
function handleSelectRole(roles: number[]) {
  // 调用后端保存：给用户重新绑定角色
  console.log(`给用户 ${chooseUserId.value} 分配角色：`, roles)
  // 示例：api.saveUserRoles(chooseUserId.value, roles)
  const assign: AssignRole = {userId:chooseUserId.value,roleIds:roles}
  const res = reqAssignedRole(assign)
  res.then(r => {
    if (r.data) {
      setTimeout(() => {
      ElMessage.success('分配成功')
      visible.value = false
  }, 300)
    }
  }).catch(e => {
    setTimeout(() => {
      ElMessage.error('分配失败')
      visible.value = false
  }, 300)
  })

  
}

function handleCancel() {
  setTimeout(() => {
    visible.value = false
  }, 300)
}

// 处理编辑
const divisonRole = (row: UserResp) => {
  Object.assign(userForm, row)
  console.log('row.id==', row.userId)
  chooseUserId.value = row.userId
  selectedRoles.value = []
  visible.value = true
}

// 处理删除
// 处理删除
const handleDelete = async (userId: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const { code, message } = await reqUserDel(userId) // 等待结果
    if (code === 200) {
      ElMessage.success('删除成功')
      fetchUserList() // 成功后再刷新
    } else {
      ElMessage.error(message || '删除失败')
    }
  } catch (e) {
    // 点“取消”会进这里，接口异常也进这里
    if (e === 'cancel') return
    ElMessage.error('接口异常')
  }
}

// 分页大小变化
const handleSizeChange = (val: number) => {
  pagination.currentPage = 1
  pagination.pageSize = val
  fetchUserList()
}

// 当前页变化
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  fetchUserList()
}

// 头像上传成功处理
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  // 实际项目中这里应该返回图片URL
  userForm.avatar = URL.createObjectURL(uploadFile.raw!)
}

// 提交表单
const submitForm = async () => {
  userFormRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
  })

  let user: User = { ...userForm }
  let result: R<boolean>
  if (user.userId) {
    // 更新
    result = await reqUserUpdate(user)
  } else {
    result = await reqUserAdd(user)
  }

  if (result && result.code === 200) {
    ElMessage.success(isEditing.value ? '用户更新成功' : '用户添加成功')
    dialogVisible.value = false

    if (user.userId) {
      // 2. 取最新数据
      const { data: fresh } = await requserOne(user.userId)
      // 3. 局部替换：只更新 userId 匹配的那一行
      userList.value = userList.value.map((item) =>
        item.userId === fresh.userId ? fresh : item,
      )
    } else {
      fetchUserList()
    }
  } else {
    ElMessage.success(isEditing.value ? '用户更新失败' : '用户添加失败')
  }
}

// 切换状态
const toggleStatus = async (row: UserResp) => {
  const action = row.status === '0' ? '启用' : '禁用'
  // 实际调用API更新状态

  let user: User = { userId: row.userId, status: row.status }
  const result: R<boolean> = await reqUserUpdate(user)
  if (result && result.code === 200) {
    ElMessage.success(`已${action}用户: ${row.loginName}`)
    //  const res: R<UserResp> = await requserOne(row.userId)
    // 2. 取最新数据
    const { data: fresh } = await requserOne(row.userId)

    // 3. 局部替换：只更新 userId 匹配的那一行
    userList.value = userList.value.map((item) =>
      item.userId === fresh.userId ? fresh : item,
    )
  } else {
    ElMessage.error(`${action}用户: ${row.loginName} 失败`)
  }
}

// 重置表单
const resetForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
    Object.assign(userForm, {
      id: undefined,
      name: '',
      gender: 1,
      avatar: '',
      phone: '',
      userId: '',
      birthDate: '',
    })
  }
}

// 日期格式化
const formatDate = (date: string | Date) => {
  return date ? new Date(date).toLocaleDateString() : ''
}

// 日期时间格式化
const formatDateTime = (date: string | Date) => {
  return new Date(date).toLocaleString()
}
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.text-right {
  text-align: right;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.avatar-uploader {
  display: flex;
}
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
